﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Yunchang;
using AutoChess;
using System.Text;
using Table.Blo;
using UI;

public class AutoChessModePage : Page
{
    #region UI
    public AutoChessRewardsPanel RewardsPanel;
    public UIModelKit ModelKit;
    public CommonAnimCurve ModelMoveCurve;
    public ArtTweener[] AllTweeners;

    public Button StartBtn;
    public Button CancelBtn;

    public Button ChessInfoBtn,TaskBtn,MapBtn,ShopBtn,ShipBtn,HeroPackgeBtn,RankBtn,RewardsBtn, GameTipBtn;

    public TextureKit GradeSprite,backGround;
    public GroupSpriteKit GradeTextSprite;
    public Text GradeDuanTxt;

    //public Text RankNameMain;
    public Text RankNum;

    public Text MatchTime;
    public Text CountDownTime;
    public Text WeekCoinTxt;

    //public float MoveSpeed = 4f;
    public float MoveLengthTime = 2f;

    private System.DateTime _enterBattleTime = System.DateTime.MinValue;
    private float moveTimmer;
    #endregion

    private StringBuilder yesSB = new StringBuilder();

    private void Awake()
    {
        StartBtn.AddOnClickListener(OnClickMatchStartBtn);
        CancelBtn.AddOnClickListener(OnClickCancelMatchBtn);
       
        ChessInfoBtn.AddOnClickListener(OnClickChessInfoBtn);
        TaskBtn.AddOnClickListener(OnClickTaskBtn);
        MapBtn.AddOnClickListener(OnClickMapBtn);
        ShopBtn.AddOnClickListener(OnClickShopBtn);
        ShipBtn.AddOnClickListener(OnClickShipBtn);
        HeroPackgeBtn.AddOnClickListener(OnClickHeroPackgeBtn);
        RankBtn.AddOnClickListener(OnClickRankBtn);
        RewardsBtn.AddOnClickListener(OnClickRewardsBtn);
        GameTipBtn.AddOnClickListener(OnClickGameTipBtn);
        // todo: 
    }

    private void Update()
    {
        if (AutoChessManager.Ins.cacheData.MatchState == ProtoBuf.Message.AutoChessMatchState.MATCH)
        {
            yesSB.Clear();
            var matchTime = ServerTimerTool.CurrentTime - AutoChessManager.Ins.cacheData.StartMatchTime;
            yesSB.AppendFormat("{0:D2}:{1:D2}:{2:D2}", matchTime.Hours, matchTime.Minutes, matchTime.Seconds);
            MatchTime.text = yesSB.ToString();
        }
    }

    protected override void DoOpen()
    {
        base.DoOpen();
        Register();
        OnMatchInfoUpdate();
        AutoChessManager.Ins.cacheData.MatchPageIsOpening = true;
        SetModel();

        StartCoroutine(PlayUIAnim());
    }

    protected override void DoClose(bool immediately)
    {
        Unregister();
        AutoChessManager.Ins.cacheData.MatchPageIsOpening = false;

        base.DoClose(immediately);
    }
    public override void NotifyCoverPageRemove()
    {
        RefreshBgTexture();
    }

    #region 模型
    private void SetModel()
    {
        var hero = StaticData.playerData.role.GetCaptainHero();
        var fashionId = StaticData.playerData.dressingRoomData.OutSideShowFashionId;
        var tableModel = TableSailorModelBlo.GetTableSailorModelByHeroIdAndAppearence(hero.GetHeroId(), fashionId);
        Vector3 offset = Vector3.zero;
        float scale = 1f;
        var dictModelOffset = Table.Blo.TableHeroModelDisplayOffsetBlo.GetTableHeroModelDisplayOffset(tableModel.ModelId);
        if (dictModelOffset != null)
        {
            if (!string.IsNullOrEmpty(dictModelOffset.heroFormationPosOffset))
            {
                offset = CommonMethod.GetPosition(dictModelOffset.heroFormationPosOffset);
            }
            if (dictModelOffset.heroFormationPosScale > 0)
            {
                scale = dictModelOffset.heroFormationPosScale;
            }
        }
        ModelKit.SetOffset(offset);
        ModelKit.SetModelScale(scale);
        ModelKit.SetModel(tableModel.ModelRes);
        ModelKit.afterLoad = OnModelLoadFinish;
    }
    #endregion

    #region 消息注册回调
    private bool isRegisted = false;
    private void Register()
    {
        if (!isRegisted)
        {
            EventManager.AddEventListener(CommonEvent.ON_AUTOCHESS_MATCH_INFO_UPDATE, OnMatchInfoUpdate);
            EventManager.AddEventListener<long>(CommonEvent.ON_AUTOCHESS_MATCH_SUCCESS, OnMatchCountDownStart);
            isRegisted = true;
        }
    }
    private void Unregister()
    {
        if (isRegisted)
        {
            EventManager.RemoveEventListener(CommonEvent.ON_AUTOCHESS_MATCH_INFO_UPDATE, OnMatchInfoUpdate);
            EventManager.RemoveEventListener<long>(CommonEvent.ON_AUTOCHESS_MATCH_SUCCESS, OnMatchCountDownStart);
            isRegisted = false;
        }
    }
    private void OnMatchInfoUpdate()
    {
        var matchState = AutoChessManager.Ins.cacheData.MatchState;
        switch (matchState)
        {
            case ProtoBuf.Message.AutoChessMatchState.FREE:
                break;
            case ProtoBuf.Message.AutoChessMatchState.MATCH:
                break;
            case ProtoBuf.Message.AutoChessMatchState.FIGHT:
                break;
            default:
                break;
        }
        StartBtn.gameObject.SetActive(matchState == ProtoBuf.Message.AutoChessMatchState.FREE);
        CancelBtn.gameObject.SetActive(matchState == ProtoBuf.Message.AutoChessMatchState.MATCH || matchState == ProtoBuf.Message.AutoChessMatchState.FIGHT);
        MatchTime.transform.parent.gameObject.SetActive(matchState == ProtoBuf.Message.AutoChessMatchState.MATCH);
        RefreshBgTexture();
        var tableGrade = AutoChessBlo.GetGradeById(AutoChessManager.Ins.cacheData.Grade);
        //RankNameMain.text = tableGrade.rankType.ToString();
        if (tableGrade.subGradeType == 0)
        {
            RankNum.text = AutoChessManager.Ins.cacheData.Score.ToString();
            GradeDuanTxt.gameObject.SetActive(false);
        }
        else
        {
            RankNum.text = tableGrade.subGradeType.ToString();
            GradeDuanTxt.gameObject.SetActive(true);
        }
        GradeSprite.TextureName = tableGrade.gradeIcon;
        GradeTextSprite.SetSpriteName(tableGrade.gradeTextIcon);
        WeekCoinTxt.text = AutoChessManager.Ins.cacheData.WeekRewardCoin + "/" + Table.DataModel.TableConfig.weekRewardCoin;

        RewardsPanel.Refresh();
    }

    private void RefreshBgTexture()
    {
        backGround.TextureName = AutoChessBlo.GetMapBackGroundByChessMapId(AutoChessManager.Ins.cacheData.MainPageMapId);
    }

    private void OnMatchCountDownStart(long startTime)
    {
        //CountDownTime.gameObject.SetActive(true);
        _enterBattleTime = ServerTimerTool.Java2CSTimeLocale(startTime);
    }
    #endregion

    #region UI点击

    private void OnClickShipBtn()
    {
        PageManager.Instance.OpenPage("ChessChooseShipPage");
    }

    private void OnClickMapBtn()
    {
        PageManager.Instance.OpenPage("ChessSandShopPage");
    }

    private void OnClickMatchStartBtn()
    {
        if (LadderManager.Instance.IsExistenceMatchState())
        {
            GlobalLazyMessageManager.Instance.CreateGlobalPopTip("NotCanFight");
            return;
        }
        if (!Yunchang.Scene.GamePlayerManager.Instance.PlayerObj.IsInSafeArea)
        {
            GlobalLazyMessageManager.Instance.CreateGlobalPopTip("NotSafeAreaMatch");
            return;
        }
        if (TeamTools.PlayerIsInTeam())
        {
            GlobalLazyMessageManager.Instance.CreateGlobalPopTip("InTeamCantAutoChessMatch");
            return;
        }

        AutoChessManager.Ins.SendCSAutoChessMatch();
    }
    private void OnClickCancelMatchBtn()
    {
        AutoChessManager.Ins.SendCSCancelAutoChessMatch();
    }
    private void OnClickRewardsBtn()
    {
        RewardsPanel.gameObject.SetActive(true);
    }
    private void OnClickChessInfoBtn()
    {
        PageManager.Instance.OpenPage("ChessPokedexPage");
    }
    private void OnClickGameTipBtn()
    {
        PageManager.Instance.OpenPage("Chess_ExplainPage");
    }
    private void OnClickShopBtn()
    {
        Yunchang.PageManager.Instance.OpenPage("NPCShopPage", new UI.NpcShopPageParam()
        {
            shopTypes = new List<int>() { 26 },
            defaultIndex = 0,
            pageNames = new List<string>() { TableTextBlo.GetText("AutoChessShop") },
        });
    }

    private void OnClickRankBtn()
    { 
        PageManager.Instance.OpenPage("ChessRankPage");
    }

    private void OnClickTaskBtn()
    {
        PageManager.Instance.OpenPage("ChessWeeklyTaskPage");
    }

    private void OnClickHeroPackgeBtn()
    {
       PageManager.Instance.OpenPage("ChessPackagesPage");
    }

    #endregion

    #region Animation
    private void OnModelLoadFinish()
    {
        moveTimmer = 0;
        StartCoroutine(PlayModelAnim());
    }
    IEnumerator PlayModelAnim()
    {
        //移动
        ModelKit.PlayAnimation("walk", false);
        do
        {
            moveTimmer += Time.deltaTime;
            yield return null;

            if (moveTimmer > MoveLengthTime)
                moveTimmer = MoveLengthTime;

            var percent = moveTimmer / MoveLengthTime;
            var curPos = ModelMoveCurve.EvaluatePosition(percent);
            var curRot = ModelMoveCurve.EvaluateEulerAngle(percent);

            ModelKit.modelTrans.localPosition = curPos;
            ModelKit.modelTrans.localRotation = Quaternion.Euler(curRot);
        } while (moveTimmer < MoveLengthTime);
        yield return null;

        ModelKit.PlayAnimation("strong", true);
        yield return new WaitForSeconds(ModelKit.GetAnimationTime("strong"));

        ModelKit.PlayAnimation("stand", true);
    }
    IEnumerator PlayUIAnim()
    {
        yield return null;
        yield return null;
        yield return null;

        LoadingPanel.Instance.HideSweepMask();
        for (int i = 0; i < AllTweeners.Length; i++)
        {
            AllTweeners[i].PlayForward();
        }
    }
    #endregion
}
